import socket


from manager import NET_TYPE
from manager.Common import *


class NetManager(object):
    _instance_lock = threading.Lock()
    _first_init = True

    def __init__(self):
        if self._first_init:
            self.buff_size = 1024
            self.dict_sensor = {}
            self.udp_socket = None
            self.__class__._first_init = False
            pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            with NetManager._instance_lock:
                if not hasattr(cls, '_instance'):
                    NetManager._instance = object.__new__(cls)
        return NetManager._instance

    def __del__(self):
        pass

    @staticmethod
    def get_host_ip():
        so = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            so.connect(('8.8.8.8', 80))
            ip = so.getsockname()[0]
        finally:
            so.close()
        if ip == "":
            ip = "127.0.0.1"
        return ip

    @staticmethod
    def tcp_server_connect(ip, port):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 创建一个用于监听连接的Socket对像（服务器端）
        server.bind((ip, port))  # 设置服务端的ip和端口号
        server.listen(5)  # 开始监听

        conn, addr = server.accept()  # 接受服务器端发出的消息和地址信息'///

        # dict_para = {'conn': conn}
        # self.thread = WorkThread(dict_para)
        # self.thread.start()
        return server

    def tcp_client_connect(self, ip, port):
        pass

    def udp_connect(self, ip, port):
        udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        udp_socket.bind((ip, port))
        self.udp_socket = udp_socket

    def close_socket(self):
        if self.udp_socket is not None:
            self.udp_socket.close()

    def rev_data(self, net_type):
        rev_data = ""
        try:
            if net_type == NET_TYPE.UDP:
                # print('udp_socket:', self.udp_socket)
                data, client_addr = self.udp_socket.recvfrom(self.buff_size)
                print('server收到的数据', data)
                rev_data = data
                self.data_manager(net_type, data)
            elif net_type == NET_TYPE.TCP_SERVER:
                pass
            elif net_type == NET_TYPE.TCP_CLIENT:
                pass
            else:
                pass
        except IOError:
            print('io error')
        return rev_data, self.dict_sensor

    def init_charge_sensor(self):
        self.dict_sensor['charge_side_open'] = -1
        self.dict_sensor['charge_charging'] = -1
        self.dict_sensor['charge_v'] = '12.5'
        self.dict_sensor['charge_v'] = '0.5'

    def init_change_sensor(self):
        self.dict_sensor['change_up'] = -1
        self.dict_sensor['change_down'] = -1
        self.dict_sensor['change_center'] = -1
        self.dict_sensor['change_new_init'] = -1
        self.dict_sensor['change_new_work'] = -1
        self.dict_sensor['change_old_init'] = -1
        self.dict_sensor['change_old_work'] = -1
        self.dict_sensor['change_new_paste'] = -1
        self.dict_sensor['change_old_on'] = '-2000'
        self.dict_sensor['change_new_on'] = '-1000'
        self.dict_sensor['change_clean_on'] = '-1000'
        self.dict_sensor['change_pad_on'] = -1
        self.dict_sensor['change_new_mop_on'] = '-1000'
        self.dict_sensor['change_old_mop_on'] = -1
        self.dict_sensor['change_lift_a'] = '-1000'
        self.dict_sensor['change_new_move_a'] = '-1000'
        self.dict_sensor['change_old_move_a'] = '-1000'

    def init_watering_sensor(self):
        self.dict_sensor['watering_water_level'] = -1
        self.dict_sensor['watering_leak'] = '-1000'
        self.dict_sensor['watering_tank_pos'] = '-1000'
        self.dict_sensor['watering_tank_light'] = '-1000'
        self.dict_sensor['watering_auto_a'] = '-1000'

    def init_dust_sensor(self):
        self.dict_sensor['dust_bag_on'] = -1
        self.dict_sensor['dust_up_open'] = -1
        self.dict_sensor['dust_pressure'] = '-1000'
        self.dict_sensor['dust_auto_a'] = '-1000'

    def clear_dict_sensor(self):
        self.dict_sensor.clear()

    def data_manager(self, manage_type, data: bytes):
        if manage_type == NET_TYPE.UDP:
            if data != '':
                Common.data_paste(data, self.dict_sensor)
        return self.dict_sensor

    def sendto(self, bytes_send, ip, port):
        address = (ip, port)
        self.udp_socket.sendto(bytes_send, address)
